import axios from 'axios'
import Vue from 'vue'

Vue.prototype.$http = axios

/**
 * @param url
 * @param method get|post|put|delete...
 * @param params like queryString. if a url is index?a=1&b=2, params = {a: '1', b: '2'}
 * @param data post data, use for method put|post
 * @returns {Promise}
 */
function ajax (url, method, { params = {}, data = {} }) {
  axios.defaults.baseURL = '/api'
  return new Promise((resolve, reject) => {
    axios({
      url,
      method,
      params,
      data
    }).then(res => {
      if (res.data.error != null) {
        reject(res)
      } else {
        resolve(res)
      }
    }, res => {
      reject(res)
    })
  })
}

export default {
  GetData (offset, limit, searchParams) {
    let params = {
      offset,
      limit
    }
    if (searchParams) {
      Object.keys(searchParams).forEach((element) => {
        if (searchParams['name']) {
          params['name'] = searchParams['name']
        }
        if (searchParams['DataRange']) {
          params['beginDate'] = searchParams['DataRange'][0]
          params['endDate'] = searchParams['DataRange'][1]
        }
      })
    }
    return ajax('GetData', 'get', {
      params: params
    })
  },
  AddData (date) {
    return ajax('AddData', 'post', {
      data: date
    })
  },
  EditData (date) {
    return ajax('EditData', 'put', {
      data: date
    })
  },
  DeleteData (id) {
    return ajax('DeleteData', 'delete', {
      params: {
        id
      }
    })
  },
  StatisticsData (searchParams) {
    let params = {}
    if (searchParams) {
      Object.keys(searchParams).forEach((element) => {
        if (searchParams['DataRange']) {
          params['beginDate'] = searchParams['DataRange'][0]
          params['endDate'] = searchParams['DataRange'][1]
        }
      })
    }
    return ajax('StatisticsData', 'get', {
      params: params
    })
  }
}
